package com.csf.controller;

import com.csf.config.likeKeyConfig;
import com.csf.entity.User;
import com.csf.service.UserService;
import com.csf.util.CommunityActivation;
import com.csf.util.communityUtils;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

@Controller
public class LoginController implements CommunityActivation {

    @Autowired
    private UserService userService;
//    验证码
    @Autowired
    private Producer kaptchaPro;

//
    @Autowired
    private RedisTemplate redisTemplate;

//跳转至注册界面
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public String register(){
        return "/site/register";
    }
//    跳转至登陆界面
    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String login(){
        return "/site/login";
    }
//    设置登陆界面的验证码
    @RequestMapping(value = "/captcha",method = RequestMethod.GET)
    public void getCaptcha(HttpServletResponse response){
//      生成随机数和图片
        String text = kaptchaPro.createText();
        BufferedImage image = kaptchaPro.createImage(text);
//        将text放入session中，以备与输入的验证码匹配
//        session.setAttribute("text",text);

//       首先生成特定标识符
        String indetiCount = communityUtils.getRandom();
//        放入cookie中
        Cookie cookie = new Cookie("indetiCount",indetiCount);
        cookie.setPath("/");
        cookie.setMaxAge(60);
        response.addCookie(cookie);
//        生成key名
        String kaptchaName = likeKeyConfig.getCaptchaName(indetiCount);
        redisTemplate.opsForValue().set(kaptchaName,text);

//将图片给浏览器(以哪种形式哪种格式上传)
        response.setContentType("image/png");
//       用什么流上传
        try {
//            以流的形式上传，整个流程走完我们不需要关流，根据spring的特性会帮我们关流
            ServletOutputStream stream = response.getOutputStream();
//
            ImageIO.write(image,"png",stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//    接收注册界面信息
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String register(Model model, User user){
        Map<String, Object> register = userService.register(user);
        if (register == null || register.isEmpty()){
               model.addAttribute("msg","注册成功！我们已发送一条账户激活邮件，请您点击尽快激活！");
               model.addAttribute("target","/discuss/findDis");
               return "/site/operate-result";
        }else{
            //如果不是，则表明有错误
             model.addAttribute("usernameMsg",register.get("usernameMsg"));
             model.addAttribute("passwordMsg",register.get("passwordMsg"));
             model.addAttribute("emailMsg",register.get("emailMsg"));
             return "/site/register";
        }
    }

    @RequestMapping(value = "/activation/{userId}/{code}",method = RequestMethod.GET)
    public String activation(Model model, @PathVariable("userId") int userId,@PathVariable("code")String code){
        int code1 = userService.activationCode(userId, code);
        if (code1 == ACTIVATION_SUCCESS){
            model.addAttribute("msg","恭喜激活成功，现在可以正常使用您的牛客帐号了");
            model.addAttribute("target","/login");
        }else if (code1 == AVTIVATION_REPEAT){
            model.addAttribute("msg","该账号已经激活，请勿重新激活！");
            model.addAttribute("target","/discuss/findDis");
        }else if (code1 == ACTIVATION_FAILSE){
            model.addAttribute("msg","激活失败！");
            model.addAttribute("target","/discuss/findDis");
        }
        return "/site/operate-result";
    }

//    登录
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String username,String password,String code,boolean rememberme,Model model,
                        HttpServletResponse response,@CookieValue("indetiCount") String indetiCount){
        //从session域中获取验证码并验证
//        String  text = (String)session.getAttribute("text");

//        从cookie中获取标识符，然后拼接
        String captchaName = likeKeyConfig.getCaptchaName(indetiCount);
        String text = (String) redisTemplate.opsForValue().get(captchaName);

        if (StringUtils.isBlank(text) || StringUtils.isBlank(code) || !text.equals(code)){
            model.addAttribute("codeMsg","验证码错误");
            return "/site/login";
        }
//        判断是否记住账户
        int Time_Long = rememberme?REMEMBER_TIME_LONG:DEFAULT_TIME_LONG;
//        处理密码

        Map<String, Object> login = userService.login(username, password, Time_Long);
        if (login.containsKey("ticket")){
            Cookie cookie = new Cookie("ticket",login.get("ticket").toString());
            cookie.setPath("/");
            cookie.setMaxAge(Time_Long);
            response.addCookie(cookie);
            return "redirect:/discuss/findDis";
        }else {
            model.addAttribute("usernameMsg",login.get("usernameMsg"));
            model.addAttribute("passwordMsg",login.get("passwordMsg"));
            return "/site/login";
        }

    }

    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String loginOut(@CookieValue("ticket") String ticket){
        SecurityContextHolder.clearContext();
         userService.updateTicket(ticket);
         return "redirect:/login";
    }
}
